package com.blueocean_health.care.management.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.OrderChargeInfo;
import com.blueocean_health.care.management.domain.base.OrderInfo;
import com.blueocean_health.care.management.domain.base.OrderRefundInfo;
import com.blueocean_health.care.management.domain.base.OrderServiceInfo;
import com.blueocean_health.care.management.domain.base.Selectzhdzlist;
import com.blueocean_health.care.management.domain.base.User;
import com.blueocean_health.care.management.domain.base.UserPatient;
import com.blueocean_health.care.management.domain.dto.AppOrderDetailDto;
import com.blueocean_health.care.management.domain.dto.AppOrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.AppOrderSelectStatusEntity;
import com.blueocean_health.care.management.domain.dto.AppReceiptDetail;
import com.blueocean_health.care.management.domain.dto.AppSelectOrderInfoDto;
import com.blueocean_health.care.management.domain.dto.AppSickRoomInfoDto;
import com.blueocean_health.care.management.domain.dto.AppWorkInfoDto;
import com.blueocean_health.care.management.domain.dto.AppWorkerInfoDto;
import com.blueocean_health.care.management.domain.dto.ChargeInfoDto;
import com.blueocean_health.care.management.domain.dto.OrderDetailDto;
import com.blueocean_health.care.management.domain.dto.OrderInfoDto;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoReceivableEntity;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoToChargeEntity;
import com.blueocean_health.care.management.domain.dto.RelationListDto;
import com.blueocean_health.care.management.domain.dto.SOrderInfoEntity;
import com.blueocean_health.care.management.domain.dto.SOrderServiceInfoEntity;
import com.blueocean_health.care.management.domain.dto.SOrderServiceNurseInfoEntity;
import com.blueocean_health.care.management.domain.dto.SettlementDto;
import com.blueocean_health.care.management.domain.dto.SickRoomInfoDto;
import com.blueocean_health.care.management.domain.dto.WorkerDto;
import com.blueocean_health.care.management.domain.dto.WorkerInfoDto;
import com.blueocean_health.care.management.domain.ordervo.SelectOrderVo;
import com.blueocean_health.care.management.domain.ordervo.ToChargeVo;
import com.blueocean_health.care.management.em.FeeTypeEnum;
import com.blueocean_health.care.management.em.OrderStatusEnum;
import com.blueocean_health.care.management.em.OrderTypeEnum;
import com.blueocean_health.care.management.em.PayStatusEnum;
import com.blueocean_health.care.management.em.PayStatusUserEnum;
import com.blueocean_health.care.management.em.RefundDealStatus;
import com.blueocean_health.care.management.em.ServiceStatusEnum;
import com.blueocean_health.care.management.em.SortEnum;
import com.blueocean_health.care.management.mapper.AppOrderSelectInfoEntityMapper;
import com.blueocean_health.care.management.mapper.OrderChargeInfoMapper;
import com.blueocean_health.care.management.mapper.OrderInfoMapper;
import com.blueocean_health.care.management.mapper.OrderSelectInfoEntityMapper;
import com.blueocean_health.care.management.mapper.OrderServiceInfoMapper;
import com.blueocean_health.care.management.mapper.SOrderInfoEntityMapper;
import com.blueocean_health.care.management.mapper.UserMapper;
import com.blueocean_health.care.management.service.IAppOrderSelectService;
import com.blueocean_health.care.management.service.IChareOrderService;
import com.blueocean_health.care.management.service.IOrderSelectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hp.hpl.sparta.Document.Index;

@Service
public class AppOrderSelectServiceImpl implements IAppOrderSelectService {
	// @Resource
	// private OrderSelectInfoEntityMapper orderSelectInfoEntityMapper;
	@Resource
	private OrderChargeInfoMapper orderChargeInfoMapper;
	@Resource
	private SOrderInfoEntityMapper sOrderInfoEntityMapper;
	@Resource
	private OrderServiceInfoMapper orderServiceInfoMapper;
	 @Resource
	 private OrderInfoMapper orderInfoMapper;
	// @Resource
	// private IChareOrderService iChareOrderService;
	// @Resource
	// private UserMapper userMapper;
	@Resource
	private AppOrderSelectInfoEntityMapper appOrderSelectInfoEntityMapper;
	@Value("${service.address.userstatic}")
	private String ADDRESSSTATIC;

	@Override
	public PageInfo<AppOrderSelectInfoEntity> appSelectOrderList(SelectOrderVo order) {
		if (null == order) {
			order = new SelectOrderVo();
			order.setPage("1");
			order.setPageSize("100");
		}
		PageHelper.startPage(Integer.valueOf(StringUtils.isEmpty(order.getPage()) ? "1" : order.getPage()),
				Integer.valueOf(StringUtils.isEmpty(order.getPageSize()) ? "65536" : order.getPageSize()));
		List<AppOrderSelectInfoEntity> selectForList = appOrderSelectInfoEntityMapper.selectForList(order);
    for (AppOrderSelectInfoEntity appOrderSelectInfoEntity : selectForList) {
    	putimgurl(appOrderSelectInfoEntity);
    	nopay(appOrderSelectInfoEntity);
    	today(appOrderSelectInfoEntity);
	}
	PageInfo<AppOrderSelectInfoEntity> pageInfo = new PageInfo<AppOrderSelectInfoEntity>(selectForList);
		return pageInfo;
	}
	private void today(AppOrderSelectInfoEntity selectForList) {
	Integer hour = Integer.valueOf(StringUtils.isEmpty(selectForList.getHour())?"0":selectForList.getHour());
	Integer day = Integer.valueOf(StringUtils.isEmpty(selectForList.getDay())?"0":selectForList.getDay());
	int i=hour/24;
	if(i>0){
		day+=i;
		hour=hour%24;
	}
	selectForList.setHour(String.valueOf(hour));
	selectForList.setDay(String.valueOf(day));
		}
	
	private void nopay(AppOrderSelectInfoEntity selectForList) {
		if(selectForList.getPayStatus().equals(PayStatusEnum._1.getKey())){
			selectForList.setTotalAmount(0.00);
		}
	}
	// 放入随机头像
	private void putimgurl(AppOrderSelectInfoEntity selectForList) {
		//int i = new Random().nextInt(3) + 1;
		
		switch (3) {
		case 1:
			selectForList.setPicAddress(ADDRESSSTATIC+"女护工.png");
			break;
		case 2:
			selectForList.setPicAddress(ADDRESSSTATIC+"男护工.png");
			break;
		case 3:
			selectForList.setPicAddress(ADDRESSSTATIC+"护工组icon.png");
			break;
		default:
			break;
		}

	}
	@Override
	public AppOrderSelectStatusEntity appSelectOrderStatus(SelectOrderVo order){
		OrderInfo lastOrderInfoById = orderInfoMapper.getLastOrderInfoById(order.getOrderId());
		AppOrderSelectStatusEntity appOrderSelectStatusEntity=new AppOrderSelectStatusEntity();
		if(null!=lastOrderInfoById){
		appOrderSelectStatusEntity.setOrderStatus(lastOrderInfoById.getOrderStatus());
		appOrderSelectStatusEntity.setPayStatus(lastOrderInfoById.getPayStatus());
		}
		return appOrderSelectStatusEntity;
	}
	@Override
	public AppSelectOrderInfoDto appSelectOrderInfo(SelectOrderVo order) {

		SOrderInfoEntity selectByPrimaryKey = sOrderInfoEntityMapper.selectByPrimaryKey(order);
		// 拼接参数
		AppSelectOrderInfoDto orderInfoDto = null;
		if (selectByPrimaryKey != null) {
			orderInfoDto = new AppSelectOrderInfoDto();
			BeanUtils.copyProperties(selectByPrimaryKey, orderInfoDto);

		} else {
			return null;
		}
		String hospitalId = selectByPrimaryKey.getHospitalId();
		String orderId = selectByPrimaryKey.getOrderId();
		Double orderAmount = 0.0;
		List<SOrderServiceInfoEntity> orderServiceInfoList = selectByPrimaryKey.getsOrderServiceInfoEntity();
		List<AppOrderDetailDto> orderDetailList = new ArrayList<AppOrderDetailDto>();
		if (orderServiceInfoList != null && orderServiceInfoList.size() > 0) {
			for (SOrderServiceInfoEntity sOrderServiceInfoEntity : orderServiceInfoList) {
				AppOrderDetailDto orderDetail = new AppOrderDetailDto();
				AppSickRoomInfoDto sickRoomInfo = new AppSickRoomInfoDto();
				BeanUtils.copyProperties(sOrderServiceInfoEntity, orderDetail);
				String timeStr = getBegin(sOrderServiceInfoEntity.getBeginTime(), sOrderServiceInfoEntity.getEndTime());
				orderDetail.setTimeStr(timeStr);
				BeanUtils.copyProperties(sOrderServiceInfoEntity, sickRoomInfo);
				sickRoomInfo.setBedNumber(sOrderServiceInfoEntity.getHospitalBed());
				BeanUtils.copyProperties(sOrderServiceInfoEntity, orderDetail);
				orderDetail.setSickRoomInfo(sickRoomInfo);
				orderAmount += sOrderServiceInfoEntity.getActualTotalPrice()==null?0:sOrderServiceInfoEntity.getActualTotalPrice();
				// 提取护工服务信息
				List<SOrderServiceNurseInfoEntity> orderServiceNurseInfoList = sOrderServiceInfoEntity
						.getSOrderServiceNurseInfoEntity();
				List<AppWorkInfoDto> workerVoList = new ArrayList<AppWorkInfoDto>();
				if (orderServiceNurseInfoList != null && orderServiceNurseInfoList.size() > 0) {
				// 服务信息一定一致 取一条
					SOrderServiceNurseInfoEntity sOrderServiceNurseInfoEntity = orderServiceNurseInfoList.get(0);
					AppWorkerInfoDto workerInfo = new AppWorkerInfoDto();
					workerInfo.setServiceType(sOrderServiceNurseInfoEntity.getServiceType());
					for (SOrderServiceNurseInfoEntity sOrderServiceNurseInfoEntity2 : orderServiceNurseInfoList) {
						AppWorkInfoDto workerVo = new AppWorkInfoDto();
						BeanUtils.copyProperties(sOrderServiceNurseInfoEntity2, workerVo);
						workerVoList.add(workerVo);
					}
					workerInfo.setWorkers(workerVoList);
					orderDetail.setWorkerInfo(workerInfo);

				} else {
//					 护工信息为空
					AppWorkerInfoDto workerInfo = new AppWorkerInfoDto();
					workerInfo.setWorkers(workerVoList);
					orderDetail.setWorkerInfo(workerInfo);
				}
				// 服务详细信息放入集合
				orderDetailList.add(orderDetail);

			}
			// 集合放进最外层
			orderInfoDto.setOrderDetail(orderDetailList);

		} else {
			// 如果服务信息为空
			orderInfoDto.setOrderDetail(new ArrayList<>());
		}
		List<AppReceiptDetail> listforAppReceipt = new ArrayList<AppReceiptDetail>();
		// 构建订单金额数据
		AppReceiptDetail firstReceipt = new AppReceiptDetail();
		DecimalFormat    df   = new DecimalFormat("######0.00");   
		firstReceipt.setValue(df.format(orderAmount));
		firstReceipt.setType("1");
		firstReceipt.setLabel("订单金额 ");
		listforAppReceipt.add(firstReceipt);
		// 查询此订单收据编号
		List<String> receiptNumByOrderId = orderChargeInfoMapper.getReceiptNumByOrderId(orderId);
		if (null != receiptNumByOrderId && receiptNumByOrderId.size() > 0) {
			String receiptNum = receiptNumByOrderId.get(0);
			// 根据收据编号查询退款单
			List<OrderChargeInfo> refundOrderbyReceiptNumber = orderChargeInfoMapper
					.getRefundOrderbyReceiptNumber(hospitalId, receiptNum);
			Double refundAmount = 0.0;
			for (OrderChargeInfo orderChargeInfo : refundOrderbyReceiptNumber) {
				// 根据退款单id查询退款单费用
				List<OrderServiceInfo> orderServiceByOrderId = orderServiceInfoMapper
						.getOrderServiceByOrderIdNew(orderChargeInfo.getOrderId());
				if (null != orderServiceByOrderId && orderServiceByOrderId.size() > 0) {
					// 构建返回数据
					orderInfoDto.setPayStatus(PayStatusUserEnum._3.getKey());
					AppReceiptDetail appReceiptDetail = new AppReceiptDetail();
					String serviceOrderTime = orderChargeInfo.getServiceOrderTime();
					String refundTimeStr = getRefundTimeStr(serviceOrderTime);
					String label = "退款金额  (" + refundTimeStr +")";
					Double actualTotalPrice = orderServiceByOrderId.get(0).getActualTotalPrice();
					refundAmount -= actualTotalPrice;
					appReceiptDetail.setLabel(label);
					appReceiptDetail.setValue(df.format(actualTotalPrice ==0?0:actualTotalPrice *-1));
					appReceiptDetail.setType("2");
					listforAppReceipt.add(appReceiptDetail);
				}
			}
			// 构建发生金额数据
			AppReceiptDetail lastReceipt = new AppReceiptDetail();
			lastReceipt.setValue(df.format(orderAmount + refundAmount));
			lastReceipt.setType("3");
			lastReceipt.setLabel("发生金额 ");
			listforAppReceipt.add(lastReceipt);
		}
		orderInfoDto.setReceiptDetail(listforAppReceipt);
		return orderInfoDto;
	}

	private String getRefundTimeStr(String oldRefundTime) {
		int indexOf = oldRefundTime.indexOf("/");
		int indexOf1 = oldRefundTime.indexOf("-");
		String beforestr = oldRefundTime.substring(indexOf + 1, indexOf1).replace("/", ".");
		int indexOf2 = oldRefundTime.indexOf("/", indexOf1);
		String afterstr = oldRefundTime.substring(indexOf2 + 1).replace("/", ".");
		return beforestr + "- " + afterstr;
	}
	private String getBegin(Date beginTime,Date endTime) {
		String beginTimeStr = "";
		if(null!=beginTime){
			beginTimeStr = TimeUtils.getStringByDate(beginTime, TimeType.MM_dd);
		}
		String endTimeStr = "";
		if(null!=endTime){
			endTimeStr = TimeUtils.getStringByDate(endTime, TimeType.MM_dd);
		}
		return "("+beginTimeStr + " - " + endTimeStr+")";
	}

	public static void main(String[] args) {
//		String str = "2018/01/19 - 2018/01/20";
//		int indexOf = str.indexOf("/");
//		int indexOf1 = str.indexOf("-");
//		String beforestr = str.substring(indexOf + 1, indexOf1).replace("/", ".");
//		int indexOf2 = str.indexOf("/", indexOf1);
//		String afterstr = str.substring(indexOf2 + 1).replace("/", ".");
//		System.out.println("(" + beforestr + "- " + afterstr + ")");
		 while (true) {
			int i= new Random().nextInt(3)+1;
			System.out.println();
		}
	}
}
